﻿using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace demo11_绘制验证码
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DrawInfo(5);
        }

        /// <summary>
        /// 随机数对象
        /// </summary>
        private Random _rnd = new Random();

        /// <summary>
        /// 随机字符串的基础字符集(字母、数字)
        /// </summary>
        private static string _baseChar = "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";

        /// <summary>
        /// 产生随机字符串(字母\数字\下划线)
        /// </summary>
        /// <returns>随机字符串</returns>
        public string RandomString(int length)
        {
            if (length <= 0) return "";
            StringBuilder sb = new StringBuilder(string.Empty);
            for (int i = 0; i < length; i++)
            {
                sb.Append(_baseChar[_rnd.Next(0, _baseChar.Length)]);
            }
            return sb.ToString();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            DrawInfo(5);
        }

        private void DrawInfo(int n)
        {
            string str = RandomString(n);   //随机验证码

            //创建GDI对象
            Bitmap bmp = new Bitmap(170, 60);
            Graphics g = Graphics.FromImage(bmp);

            //验证码
            for (int i = 0; i < n; i++)
            {
                Point p = new Point(i * 30 + 10, _rnd.Next(0, 10)); //y坐标0就可显示,这里0-10为了随机上下 , x相对固定的,为了不重合
                string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };
                Color[] colors = { Color.Blue, Color.Black, Color.Red, Color.Magenta, Color.Green };    //可百度C#颜色对照表,参考
                g.DrawString(str[i].ToString(), new Font(fonts[_rnd.Next(0, 5)], 30, FontStyle.Bold), new SolidBrush(colors[_rnd.Next(0, 5)]), p);
            }

            //干扰线
            for (int i = 0; i < 30; i++)
            {
                Point p1 = new Point(_rnd.Next(0, bmp.Width), _rnd.Next(0, bmp.Height));
                Point p2 = new Point(_rnd.Next(0, bmp.Width), _rnd.Next(0, bmp.Height));

                Color color = Color.FromArgb(_rnd.Next(150, 255), _rnd.Next(255), _rnd.Next(255), _rnd.Next(255));
                g.DrawLine(new Pen(color), p1, p2);
            }

            //干扰点
            for (int i = 0; i < 1000; i++)
            {
                Point p = new Point(_rnd.Next(0, bmp.Width), _rnd.Next(0, bmp.Height));
                Color color = Color.FromArgb(_rnd.Next(150, 255), _rnd.Next(255), _rnd.Next(255), _rnd.Next(255));
                bmp.SetPixel(p.X, p.Y, color);


                ////随机颜色点
                //bmp.SetPixel(p.X, p.Y, Color.FromArgb(_rnd.Next(150, 255), _rnd.Next(255), _rnd.Next(255), _rnd.Next(255)));
            }

            //将图片镶嵌到PictureBox中
            pictureBox1.Image = bmp;
        }
    }
}
